<template>
	<view class="order-container">
		<!-- 订单状态选项卡 -->
		<view class="order-tabs">
			<view v-for="(tab, index) in tabs" :key="index" class="tab-item" :class="{active: currentTab === index}"
				@click="switchTab(index)">
				{{tab.name}}
				<view class="tab-line" v-if="currentTab === index"></view>
			</view>
		</view>

		<!-- 订单列表 -->
		<scroll-view scroll-y class="order-list" @scrolltolower="loadMore" v-if="orderList.length > 0">
			<view class="order-item" v-for="(order, index) in orderList" :key="order.id"
				@click="viewOrderDetail(order.id)">
				<!-- 订单头部 -->
				<view class="order-header">
					<text class="order-no">订单号: {{order.orderNo}}</text>
					<text class="order-status" :style="{color: getStatusColor(order.status)}">
						{{getStatusText(order.status)}}
					</text>
				</view>

				<!-- 订单商品 -->
				<view class="order-goods">
					<view class="goods-item" v-for="(item, i) in order.items" :key="i">
						<image class="goods-image" :src="item.image" mode="aspectFill"></image>
						<view class="goods-info">
							<view class="goods-name">{{item.name}}</view>
							<view class="goods-spec">{{item.spec}}</view>
							<view class="goods-price-row">
								<text class="goods-price">¥{{item.price}}</text>
								<text class="goods-count">x{{item.count}}</text>
							</view>
						</view>
					</view>
				</view>

				<!-- 订单底部 -->
				<view class="order-footer">
					<text class="total-count">共{{order.totalCount}}件商品</text>
					<text class="total-price">合计: ¥{{order.totalPrice}}</text>
				</view>

				<!-- 订单操作按钮 -->
				<view class="order-actions">
					<template v-if="order.status === 0">
						<button class="action-btn cancel" @click.stop="cancelOrder(order.id)">取消订单</button>
						<button class="action-btn primary" @click.stop="payOrder(order.id)">去支付</button>
					</template>
					<template v-else-if="order.status === 2">
						<button class="action-btn" @click.stop="viewLogistics(order.id)">查看物流</button>
						<button class="action-btn primary" @click.stop="confirmReceipt(order.id)">确认收货</button>
					</template>
					<template v-else-if="order.status === 3">
						<button class="action-btn" @click.stop="applyAfterSale(order.id)">申请售后</button>
						<button class="action-btn" @click.stop="buyAgain(order.id)">再次购买</button>
					</template>
					<template v-else-if="order.status === 4">
						<button class="action-btn" @click.stop="deleteOrder(order.id)">删除订单</button>
					</template>
				</view>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore">
				<text>{{loading ? '加载中...' : '上拉加载更多'}}</text>
			</view>
			<view class="no-more" v-else>
				<text>没有更多了</text>
			</view>
		</scroll-view>

		<!-- 空订单提示 -->
		<view class="empty-order" v-else>
			<view class="empty-text">暂无相关订单</view>
			<button class="go-shopping" @click="goToIndex">去逛逛</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentTab: 0, // 当前选中的tab索引
				tabs: [{
						name: '全部',
						status: null
					},
					{
						name: '待付款',
						status: 0
					},
					{
						name: '待发货',
						status: 1
					},
					{
						name: '已发货',
						status: 2
					},
					{
						name: '已完成',
						status: 3
					},
					{
						name: '已关闭',
						status: 4
					}
				],
				orderList: [], // 订单列表
				page: 1, // 当前页码
				pageSize: 10, // 每页数量
				hasMore: true, // 是否有更多数据
				loading: false // 是否正在加载
			}
		},
		onLoad(options) {
			console.log(options)
			// 从url参数获取初始tab
			if (options.status) {
				this.currentTab = parseInt(options.status)+1
			}
			this.loadOrders()
		},
		methods: {
			
			// 切换tab
			switchTab(index) {
				console.log(index)
				if (this.currentTab === index) return
				this.currentTab = index
				this.page = 1
				this.hasMore = true
				this.orderList = []
				this.loadOrders()
			},

			// 加载订单数据
			async loadOrders() {
				if (this.loading || !this.hasMore) return

				this.loading = true
				uni.showLoading({
					title: '加载中...'
				})

				try {
					// 模拟API请求
					const status = this.tabs[this.currentTab].status
					const res = await this.mockApiGetOrders(status, this.page, this.pageSize)

					this.orderList = this.orderList.concat(res.list)
					this.hasMore = res.hasMore
					this.page++
				} catch (error) {
					console.error(error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
				} finally {
					this.loading = false
					uni.hideLoading()
				}
			},

			// 加载更多
			loadMore() {
				this.loadOrders()
			},

			// 模拟API获取订单数据
			mockApiGetOrders(status, page, pageSize) {
				return new Promise(resolve => {
					setTimeout(() => {
						// 模拟数据
						const mockStatus = status !== null ? [status] : [0, 1, 2, 3, 4]
						const allOrders = this.generateMockOrders(mockStatus)
						const start = (page - 1) * pageSize
						const end = start + pageSize
						const list = allOrders.slice(start, end)

						resolve({
							list,
							hasMore: end < allOrders.length
						})
					}, 500)
				})
			},

			// 生成模拟订单数据
			generateMockOrders(statusList) {
				const statusTexts = ['待付款', '待发货', '已发货', '已完成', '已关闭']
				const orders = []

				for (let i = 0; i < 50; i++) {
					const status = statusList[Math.floor(Math.random() * statusList.length)]
					const itemCount = 1

					const items = []
					let totalPrice = 0

					for (let j = 0; j < itemCount; j++) {
						const price = (Math.random() * 100 + 20).toFixed(2)
						items.push({
							id: `${i}-${j}`,
							name: `商品名称${i}-${j}`,
							spec: `规格: ${['S','M','L','XL'][j%4]} ${['红色','蓝色','黑色','白色'][j%4]}`,
							price: price,
							count: Math.floor(Math.random() * 3) + 1,
							image: `/static/product${j%4+1}.jpg`
						})
						totalPrice += parseFloat(price) * items[j].count
					}

					orders.push({
						id: `order${i}`,
						orderNo: `NO${Date.now()}${i}`.slice(0, 16),
						status: status,
						statusText: statusTexts[status],
						createTime: new Date(Date.now() - Math.random() * 7 * 24 * 3600 * 1000).toLocaleString(),
						items: items,
						totalCount: items.reduce((sum, item) => sum + item.count, 0),
						totalPrice: totalPrice.toFixed(2)
					})
				}

				// 按状态和时间排序
				return orders.sort((a, b) => {
					if (a.status !== b.status) return a.status - b.status
					return new Date(b.createTime) - new Date(a.createTime)
				})
			},

			// 获取订单状态文本
			getStatusText(status) {
				const texts = ['待付款', '待发货', '已发货', '已完成', '已关闭']
				return texts[status] || ''
			},

			// 获取订单状态颜色
			getStatusColor(status) {
				const colors = ['#f56c6c', '#e6a23c', '#409eff', '#67c23a', '#909399']
				return colors[status] || '#909399'
			},

			// 查看订单详情
			viewOrderDetail(orderId) {
				uni.navigateTo({
					url: `/pages/order/detail?id=${orderId}`
				})
			},

			// 取消订单
			cancelOrder(orderId) {
				uni.showModal({
					title: '提示',
					content: '确定要取消该订单吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							})
							setTimeout(() => {
								uni.hideLoading()
								uni.showToast({
									title: '订单已取消'
								})
								this.refreshCurrentTab()
							}, 1000)
						}
					}
				})
			},

			// 支付订单
			payOrder(orderId) {
				uni.navigateTo({
					url: `/pages/order/payment?id=${orderId}`
				})
			},

			// 查看物流
			viewLogistics(orderId) {
				uni.navigateTo({
					url: `/pages/order/logistics?id=${orderId}`
				})
			},

			// 确认收货
			confirmReceipt(orderId) {
				uni.showModal({
					title: '提示',
					content: '请确认已收到商品，确认后将完成交易',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							})
							setTimeout(() => {
								uni.hideLoading()
								uni.showToast({
									title: '确认收货成功'
								})
								this.refreshCurrentTab()
							}, 1000)
						}
					}
				})
			},

			// 申请售后
			applyAfterSale(orderId) {
				uni.navigateTo({
					url: `/pages/afterSale/apply?id=${orderId}`
				})
			},

			// 再次购买
			buyAgain(orderId) {
				uni.showLoading({
					title: '加入购物车...'
				})
				setTimeout(() => {
					uni.hideLoading()
					uni.showToast({
						title: '商品已加入购物车'
					})
					uni.switchTab({
						url: '/pages/cart/cart'
					})
				}, 1000)
			},

			// 删除订单
			deleteOrder(orderId) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该订单吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '删除中...'
							})
							setTimeout(() => {
								uni.hideLoading()
								uni.showToast({
									title: '订单已删除'
								})
								this.refreshCurrentTab()
							}, 1000)
						}
					}
				})
			},

			// 刷新当前tab数据
			refreshCurrentTab() {
				this.page = 1
				this.hasMore = true
				this.orderList = []
				this.loadOrders()
			},

			// 去首页
			goToIndex() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		}
	}
</script>

<style>
.order-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f7f7f7;
}

.order-tabs {
  display: flex;
  height: 90rpx;
  background-color: #fff;
  position: sticky;
  top: 0;
  z-index: 10;
  flex-shrink: 0;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #e74c3c;
  font-weight: bold;
}

.tab-line {
  position: absolute;
  bottom: 0;
  width: 80rpx;
  height: 4rpx;
  background-color: #e74c3c;
  border-radius: 2rpx;
}

.order-list {
	height: 1rpx;
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
}

.order-item {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  padding: 20rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.order-no {
  font-size: 26rpx;
  color: #999;
}

.order-status {
  font-size: 26rpx;
  font-weight: bold;
}

.order-goods {
  padding: 20rpx;
}

.goods-item {
  display: flex;
  margin-bottom: 20rpx;
}

.goods-item:last-child {
  margin-bottom: 0;
}

.goods-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
}

.goods-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.goods-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-spec {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.goods-price-row {
  display: flex;
  justify-content: space-between;
  margin-top: 10rpx;
}

.goods-price {
  font-size: 28rpx;
  color: #e74c3c;
  font-weight: bold;
}

.goods-count {
  font-size: 26rpx;
  color: #999;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
  padding: 20rpx;
  border-top: 1rpx solid #f5f5f5;
  border-bottom: 1rpx solid #f5f5f5;
}

.total-count {
  font-size: 26rpx;
  color: #999;
  margin-right: 20rpx;
}

.total-price {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.order-actions {
  display: flex;
  justify-content: flex-end;
  padding: 20rpx;
}

.action-btn {
  height: 60rpx;
  line-height: 60rpx;
  padding: 0 30rpx;
  font-size: 26rpx;
  color: #666;
  background-color: #fff;
  border: 1rpx solid #ddd;
  border-radius: 30rpx;
  margin-left: 20rpx;
}

.action-btn.primary {
  color: #e74c3c;
  border-color: #e74c3c;
}

.action-btn.cancel {
  color: #999;
  border-color: #ddd;
}

.load-more, .no-more {
  text-align: center;
  padding: 30rpx 0;
  font-size: 26rpx;
  color: #999;
}

.empty-order {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-bottom: 100rpx;
}

.empty-order image {
  width: 300rpx;
  margin-bottom: 40rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
  margin-bottom: 40rpx;
}

.go-shopping {
  width: 240rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #e74c3c;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}
</style>